package com.kedacom.demo.springrabbit.transaction;

import java.util.UUID;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kedacom.demo.springrabbitex.Message;

@Service
@Transactional
public class MessageSender {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Resource
	private JdbcTemplate jdbcTemplate;
	@Resource
	private RabbitTemplate rabbitTemplate;

	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public RabbitTemplate getRabbitTemplate() {
		return rabbitTemplate;
	}

	public void setRabbitTemplate(RabbitTemplate rabbitTemplate) {
		this.rabbitTemplate = rabbitTemplate;
	}

	public void sendMessage() {
		// save bussiness data
		logger.debug("save business data.");
		jdbcTemplate.execute("insert into users(name) values('" + UUID.randomUUID().toString() + "')");

		// send message
		logger.debug("send message.");
		rabbitTemplate.convertAndSend(new Message("transaction message"));
	}

	public void bussinessRollback() {
		// save bussiness data
		logger.debug("save business data.");
		jdbcTemplate.execute("insert into users(name) values('luocanfeng')");
		jdbcTemplate.execute("insert into users(name) values('luocanfeng')");

		// send message
		logger.debug("send message.");
		rabbitTemplate.convertAndSend(new Message("bussiness rollback message"));
	}

	public void messageRollback() {
		// save bussiness data
		logger.debug("save business data.");
		jdbcTemplate.execute("insert into users(name) values('" + UUID.randomUUID().toString() + "')");

		// send message
		logger.debug("send message.");
		rabbitTemplate.convertAndSend("error.transaction.exchange", "error.transaction.routingkey", new Message(
				"message rollback message"));
	}

	public void bussinessRollback2() {
		// send message
		logger.debug("send message.");
		rabbitTemplate.convertAndSend(new Message("bussiness rollback message2"));

		// save bussiness data
		logger.debug("save business data.");
		jdbcTemplate.execute("insert into users(name) values('luocanfeng')");
		jdbcTemplate.execute("insert into users(name) values('luocanfeng')");
	}

}
